import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:base_moudle/index.dart';
import 'package:custom_form/feature_custom_form/models/project_base_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import '../../../../feature_personal/personal_form/index.dart';
import '../../../../feature_personal/personal_home/models/industy_model.dart';
import '../../../../feature_personal/personal_home/pages/daily_work/daily_work.dart';
import '../../../../feature_personal/personal_home/pages/daily_work/form_wating_coding.dart';
import '../../../../feature_personal/personal_home/pages/safety_quality/step_check.dart';
import '../../../../feature_personal/personal_problems/index.dart';
import '../../../../feature_personal/personal_project/index.dart';
import '../../../../feature_personal/personal_project/project_create/view.dart';
import '../../../../feature_personal/personal_project/project_files_dir.dart';
import '../../../../models/data_model/HyWorkModel.dart';
import '../../../../new_paltform/define/hy_header.dart';
import '../../db/work_app_model.dart';
import '../../setting/work_setting.dart';
import '../add_often_used/hy_add_often_used_page.dart';
import '../add_often_used/popup_menu_button/popup_menu_util.dart';
import '../add_often_used/popup_menu_button/tap_item.dart';
import '../drawer/hy_work_store_drawer_page.dart';
import '../hy_work_app_button.dart';
import 'hy_me_work_logic.dart';

class HYMeWorkDetailPage extends StatefulWidget {
  HYMeWorkDetailPage();

  @override
  _HYMeWorkDetailPageState createState() => _HYMeWorkDetailPageState();
}

class _HYMeWorkDetailPageState extends State<HYMeWorkDetailPage>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  RxDouble rx_height = (Get.height * 0.5).obs;

  List<String> appsTypes = ItemModel.myAppTypes();
  HyMeWorkHomeLogic controller = Get.put(HyMeWorkHomeLogic());
  late TabController _tabController;

  void initData() {
    _tabController = TabController(vsync: this, length: appsTypes.length);
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() => PageViewBase(
          status: controller.pageStatus.value,
          backgroundColor: Colors.white,
          onRetry: () {
            controller.onAllData();
          },
          body: RfListView(
            enablePullUp: false,
            itemCount: 2,
            indexedWidgetBuilder: (BuildContext c, int i) {
              if (i == 0) {
                return _buildBannerView();
              } else if (i == 1) {
                return _buildIntroduceCell();
              } else {
                return Obx(() => _buildAllApp());
              }
            },
          ),
        ));
  }

  Widget placeholder() {
    return zs_round_radius_contianer(
        margin: const EdgeInsets.all(15),
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SpinKitThreeBounce(
              color: Colors.black26,
            ),
            Center(
              child: ZsText('数据加载中'),
            )
          ],
        ).paddingOnly(top: 80, bottom: 80));
  }

  Widget _buildIntroduceCell() {
    return zs_round_radius_contianer(
        margin: const EdgeInsets.all(15),
        padding: EdgeInsets.zero,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // _companyName(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ZsText(
                  '我的常用',
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                  left: 1,
                ),
                Row(
                  children: [
                    HYButton.icon(
                      icon: Image.asset(
                        'assets/images/project/work_add.png',
                        width: 20,
                        height: 20,
                      ),
                      title: '添加',
                      textColor: ColorHex('#207EFA'),
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                      gap: 0,
                      onPressed: () {
                        routeNative('添加');
                      },
                    ).marginOnly(right: 10),
                    HYButton.icon(
                      icon: Image.asset(
                        'assets/images/project/work_manage.png',
                        width: 20,
                        height: 20,
                      ),
                      title: '管理',
                      textColor: ColorHex('#207EFA'),
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                      gap: 0,
                      onPressed: () {
                        routeNative('管理');
                      },
                    ).marginOnly(right: 7),
                  ],
                )
              ],
            ).intoContainer(
              height: 48,
            ),
            Obx(() => _buildItemsCell(
                  itemModelList: controller.itemList,
                  longBool: true,
                )),
          ],
        ));
  }

  Widget _buildItemsCell(
      {required List<ItemModel> itemModelList,
      bool isSelect = true,
      bool longBool = false}) {
    if (longBool == false && itemModelList.isEmpty) {
      return Column(
        children: [
          Image.asset(
            'assets/images/empty_data.png',
            height: 200,
            fit: BoxFit.cover,
          ),
          ZsText(
            '暂无数据',
            textAlign: TextAlign.center,
            color: zs_color_ccc,
            bottom: 20,
          )
        ],
      );
    }
    if (longBool == false) {
      final int count = (itemModelList.length / 4).ceil();
      final double h = (Get.width - 30) * 5 / 16;
      final double newHeight = h * count + (count - 1) * 10 + 20 + 60;
      if (newHeight > rx_height.value) {
        rx_height.value = newHeight;
      }
    }

    return Container(
      padding: EdgeInsets.zero,
      child: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            crossAxisSpacing: 10,
            childAspectRatio: 0.8,
            mainAxisSpacing: 10),
        physics: const NeverScrollableScrollPhysics(),
        //增加
        shrinkWrap: true,
        //增加
        itemCount: isSelect ? itemModelList.length + 1 : itemModelList.length,
        itemBuilder: (BuildContext ctx, int index) {
          if (index == itemModelList.length) {
            return Column(
              children: [
                Image.asset(
                  'assets/images/project/work_add_app.png',
                  fit: BoxFit.fitWidth,
                ).intoContainer(
                    height: size_wh,
                    width: size_wh,
                    margin: const EdgeInsets.only(top: 10, bottom: 10)),
                ZsText(
                  '添加常用',
                  textAlign: TextAlign.center,
                  fontSize: 13,
                  maxLines: 1,
                )
              ],
            ).intoGestureDetector(onTap: () {
              routeNative('添加常用');
            });
          } else {
            final ItemModel model = itemModelList[index];
            return buildGardViewItem(model, longBool);
          }
        },
      ),
    );
  }

  Widget buildGardViewItem(ItemModel model, bool longBool) {
    if (longBool == true) {
      return LayoutBuilder(
        builder: (BuildContext p0, BoxConstraints p1) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onLongPressStart: (LongPressStartDetails details) async {
              HapticFeedback.mediumImpact();
              await PopupMenuUtil.showPopupMenu(context, details, p1, [
                TapItem(
                  img: 'assets/images/project/project_remove.png',
                  text: '移除',
                  onTap: () {
                    controller.itemList.remove(model);
                    controller.onUpdateLike();
                  },
                ),
                TapItem(
                  img: 'assets/images/project/project_sort.png',
                  text: '排序',
                  onTap: () {
                    routeNative('管理');
                  },
                )
              ]);
            },
            child: HyWorkAppImageButton(
              buttomItem: model,
              onPressed: () {
                //注释：单击处理
                routeNative(model.title);
                HyWorkAppModel.saveClickModel(model: model, code: 2)
                    .whenComplete(() => controller.onTimeList());
              },
            ),
          );
        },
      );
    } else {
      return HyWorkAppImageButton(
        buttomItem: model,
        onPressed: () {
          //注释：单击处理
          routeNative(model.title);
          HyWorkAppModel.saveClickModel(model: model, code: 2)
              .whenComplete(() => controller.onTimeList());
        },
      );
    }
  }

  Widget _buildAllApp() {
    return HYContainer(
      // margin: const EdgeInsets.all(15),
      child: Column(
        children: [
          ZsText(
            '全部应用',
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ).intoContainer(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(top: 19, left: 16, bottom: 6)),
          DefaultTabController(
            length: appsTypes.length,
            child: Column(
              children: [
                HYContainer(
                  alignment: Alignment.centerLeft,
                  border: Border(bottom: BorderSide(color: zs_color_f2)),
                  padding: const EdgeInsets.only(right: 16),
                  child: Stack(
                    alignment: Alignment.centerLeft,
                    children: [
                      TabBar(
                        labelColor: zs_mainColor,
                        labelStyle: const TextStyle(
                            fontSize: 14, fontWeight: FontWeight.bold),
                        unselectedLabelStyle: const TextStyle(fontSize: 14),
                        unselectedLabelColor: zs_black_333,
                        indicatorSize: TabBarIndicatorSize.label,
                        indicatorColor: zs_mainColor,
                        overlayColor:
                            MaterialStateProperty.all(Colors.transparent),
                        isScrollable: true,
                        controller: _tabController,
                        tabs: appsTypes
                            .map((String e) => Tab(
                                  text: e,
                                ))
                            .toList(),
                      ).marginOnly(right: 45),
                      if (appsTypes.length > 4)
                        Align(
                          alignment: Alignment.centerRight,
                          child: HYContainer(
                            padding: const EdgeInsets.fromLTRB(5, 5, 0, 5),
                            child: Image.asset(
                              'assets/images/project/work_store.png',
                              width: 18,
                              height: 14,
                            ),
                            onTap: () {
                              HyWorkStoreDrawerPage.push(
                                      arr: appsTypes,
                                      context: context,
                                      seleted: _tabController.index)
                                  ?.then((String? value) {
                                if (value != null) {
                                  final int selectIndex =
                                      appsTypes.indexOf(value);
                                  _tabController.animateTo(selectIndex);
                                }
                              });
                            },
                          ),
                        ),
                    ],
                  ),
                ),
                Expanded(
                    child: TabBarView(
                        controller: _tabController,
                        children: appsTypes
                            .map((String e) => _buildTabBarView(e))
                            .toList()))
              ],
            ),
          ).intoContainer(height: rx_height.value),
        ],
      ),
    );
  }

  Widget _buildTabBarView(String str) {
    List<ItemModel> list = [];
    if (str == '最近使用') {
      list = controller.timeList;
    } else if (str == '全部应用') {
      list = controller.allList;
    } else {
      list = controller.allList
          .where((ItemModel element) => element.type == str)
          .toList();
    }

    return SingleChildScrollView(
      child: _buildItemsCell(itemModelList: list, isSelect: false),
    ).marginOnly(top: 10, left: 15, right: 15);
  }

  Widget _buildBannerView() {
    return HYContainer(
      margin: const EdgeInsets.fromLTRB(16, 16, 16, 9),
      // height: (Get.width - 32) * (132 / 342.0),
      child: Image.asset('assets/images/project/work_me_banner.png'),
    );
  }

  ///跳转质量控制
  _toQulityControl() {
    if (controller.zsIndustryModel.isEmpty) {
      controller.onGetClassificationIndustry().whenComplete(() {
        if (controller.zsIndustryModel.isNotEmpty) {
          showDialog(controller.zsIndustryModel, (industryNature) {
            _pushQuality(industryNature);
          });
        }
      });
    } else {
      showDialog(controller.zsIndustryModel, (industryNature) {
        _pushQuality(industryNature);
      });
    }
  }

  ///跳转安全管理
  void _toSafetyControl() {
    if (controller.zsIndustryModel.isEmpty) {
      controller.onGetClassificationIndustry().whenComplete(() {
        if (controller.zsIndustryModel.isNotEmpty) {
          showDialog(controller.zsIndustryModel, (industryNature) {
            _pushSafety(industryNature);
          });
        }
      });
    } else {
      showDialog(controller.zsIndustryModel, (industryNature) {
        _pushSafety(industryNature);
      });
    }
  }

  void _pushSafety(industryNature) {
    HRoutor.push(context,
        page: StepCheckPage(
          industryNature: industryNature,
          standardType: 'f4bc8629c1ff41d88b85e4f696f5eddc',
          formName: '',
          title: '安全管理',
          tableName: 'sys_safety_checklist',
          formId: 'f37a8f832cbb406cbbd0540049e510f9',
        ));
  }

  void _pushQuality(industryNature) {
    HRoutor.push(context,
        page: StepCheckPage(
          industryNature: industryNature,
          standardType: 'f4e1c7632ca8446faecc320340b71a86',
          formName: '',
          title: '质量控制',
          tableName: 'sys_quality_check',
          formId: 'eff4d3463da94b32831afe4c590a0396',
        ));
  }

  void showDialog(List<ZsIndustryModel> dataList, callback) {
    Picker(
        adapter: PickerDataAdapter<ZsIndustryModel>(
            pickerData: dataList,
            data: dataList
                .map((ZsIndustryModel e) => PickerItem<ZsIndustryModel>(
                    text: ZsText(e.dictLabel ?? '')))
                .toList()),
        title: const Text(
          '请选择行业性质',
          style: TextStyle(fontSize: 16),
        ),
        height: 220,
        cancelText: '取消',
        confirmText: '确认',
        cancelTextStyle: TextStyle(color: zs_black_999),
        confirmTextStyle: TextStyle(color: zs_mainColor),
        onConfirm: (Picker picker, List value) {
          final int index = value.first;
          final String? industryNature = dataList[index].id;
          callback(industryNature);
        }).showModal(context);
  }

  ///跳转日常任务
  void _toDalyWorks() {
    HRoutor.push(context, page: DailyWorkWidget());
  }

  ///跳转项目资料
  void _toProjectFiles() {
    ///取已保存的项目，娶不到？再请求接口
    ProjectBaseModel.toProjectEntity().then((ProjectBaseModel? value) {
      if (value != null) {
        HRoutor.push(context,
            page: ZsProjectFilesDirPage(
                projectId: value.projectId.toString(),
                projectName: value.projectName));
      } else {
        EasyLoading.show(status: '正在加载');
        controller.onGetFindNearProject().then((ResultData? value) {
          if (value?.isSuccess ?? false) {
            if (value?.data == null) {
              _handleNoProject();
            }
            final ProjectBaseModel data =
                ProjectBaseModel.fromJson(value!.data);
            ProjectBaseModel.toStonge(data);
            HRoutor.push(context,
                page: ZsProjectFilesDirPage(
                    projectId: data.projectId, projectName: data.projectName));
          }
        });
      }
    });
  }

  ///处理没有项目时，去添加项目
  void _handleNoProject() {
    AwesomeDialog(
      context: context,
      dialogType: DialogType.NO_HEADER,
      animType: AnimType.BOTTOMSLIDE,
      title: '提示',
      desc: '是否前往创建项目',
      btnCancelText: '取消',
      btnCancelColor: zs_black_999,
      btnOkColor: zs_mainColor,
      btnOkText: '确定',
      btnCancelOnPress: () {},
      btnOkOnPress: () async {
        HRoutor.push(context,
            page: ZsProjectCreatePage(
              canEdit: true,
              isAdd: true,
              onPop: () {
                setState(() {});
              },
            ));
      },
    ).show();
  }

  void routeNative(String key) {
    switch (key) {
      case '管理':
        HyWorkSettingPage.push(controller.itemList)?.then((value) {
          if (value is List<ItemModel>) {
            controller.itemList.value = value;
            controller.onUpdateLike();
          }
        });
        break;
      case '添加常用':
      case '添加':
        HYAddOftenUsedPage.push(code: 2)?.then((dynamic value) {
          print('返回了');
          controller.onAllData();
        });
        break;
      case '质量控制':
        _toQulityControl();
        break;
      case '安全管理':
        _toSafetyControl();
        break;
      case '日常任务':
        _toDalyWorks();
        break;
      case '资料汇总':
        _toProjectFiles();
        break;
      case '我的项目':
        HRoutor.push(context, page: ZsPersonalProjectPage());
        break;
      case '项目表单':
        HRoutor.push(context, page: ZsPersonalFormPage());
        break;
      case '项目问题':
        HRoutor.push(context, page: ZsPersonalProblemsPage());
        break;
      default:
        HRoutor.push(context, page: WatingCodingPage(key));
        break;
    }
  }

  @override
  void dispose() {
    Get.delete<HyMeWorkHomeLogic>();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    controller.onLoadData();
    initData();
  }

  @override
  bool get wantKeepAlive => true;
}
